package com.jd.org.controller;

import com.jd.basic.annotation.PreAuthorize;
import com.jd.basic.util.AjaxResult;
import com.jd.basic.util.PageList;
import com.jd.org.domain.Employee;
import com.jd.org.query.EmployeeQuery;
import com.jd.org.service.IEmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/employee")
@Api(value = "员工的API", description = "员工相关的CRUD功能")
public class EmpolyeeController {

    @Autowired
    private IEmployeeService employeeService;

    /**
     * 查询所有
     * @return
     */
    @GetMapping
    @ApiOperation(value = "查询所有" )
    @PreAuthorize(name = "查询所有",sn = "employee:findAll")
    public List<Employee> findAll(){
        return employeeService.findAll();
    }

    /**
     * 查询单个
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "查询单个" )
    public Employee findOne(@PathVariable("id") Long id){
        return employeeService.findOne(id);
    }

    /**
     * 删除单个
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除单个" )
    public AjaxResult del(@PathVariable("id") Long id){
        try {
            employeeService.del(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败，请稍后重试！");
        }
    }

    /**
     * 添加或者修改
     * @param employee
     * @return
     */
    @PutMapping
    @ApiOperation(value = "添加或者修改" )
    public AjaxResult addOrUpdate(@RequestBody @Validated Employee employee){
        try {
            if (employee.getId() == null){
                employeeService.add(employee);
            } else {
                employeeService.update(employee);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败，请稍后重试！");
        }
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PatchMapping
    @ApiOperation(value = "批量删除" )
    public AjaxResult patchDel(@RequestBody Long[] ids){
        try {
            employeeService.patchDel(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败，请稍后重试！");
        }
    }

    /**
     * 分页查询
     * @param employeeQuery
     * @return
     */
    @PostMapping
    @ApiOperation(value = "查询所有" )
    public PageList<Employee> queryPage(@RequestBody EmployeeQuery employeeQuery){
        return employeeService.queryPage(employeeQuery);
    }

}
